package com.bwsoft.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bwsoft.domain.Fun;
import com.bwsoft.domain.LogLogin;
import com.bwsoft.domain.User;
import com.bwsoft.domain.UserGroup;
import com.bwsoft.model.Message;
import com.bwsoft.model.ZTreeV;
import com.bwsoft.service.UserService;
import com.bwsoft.util.HttpUtil;
import com.bwsoft.util.MD5Util;

@SuppressWarnings("rawtypes")
@Service(UserService.NAME)
public class UserServiceImpl extends BaseServiceImpl implements UserService {

	private static Logger LOG = Logger.getLogger(UserServiceImpl.class.getClass());

	/**
	 * 验证传入用户信息是否在数据库中匹配
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Message checkUserLogin(User user) {
		Message msg = new Message();
		request = ServletActionContext.getRequest();
		session = request.getSession();
		try {
			// 1 根据用户名称去数据库中找到对应的用户
			String hql = "from User a where a.account=? ";
			List<User> users = userDao.findByHql(hql, user.getAccount());
			if (users.size() > 0) {
				// 2 查看用户是否被注销
				if (users.get(0).getStatus() == 1) {
					// 3 查看密码是否与之匹配
					if (users.get(0).getPassword().equals(MD5Util.md5_16(user.getPassword()))) {
						msg.setMsgFlag(true);
						LOG.info("登陆成功");
						session.setAttribute("User", users.get(0));
						// 记录用户登陆的日志
						logLoginDao.save(new LogLogin("用户【" + users.get(0).getName() + "】登陆系统，登陆账号为：" + user.getAccount(), new Date(), HttpUtil.getRemoteHost(request)));
					} else {
						msg.setMsgInt(2);
						msg.setMsgStr("密码错误，请重新输入");
						msg.setMsgFlag(false);
						LOG.info("密码错误，请重新输入");
					}
				} else {
					msg.setMsgInt(1);
					msg.setMsgStr("该用户名已被注销，请联系管理员");
					LOG.info("该用户名已被注销，请联系管理员");
					msg.setMsgFlag(false);
				}
			} else {
				msg.setMsgInt(1);
				msg.setMsgStr("该用户名不存在");
				LOG.info("该用户名不存在");
				msg.setMsgFlag(false);
			}

		} catch (Exception e) {
			e.printStackTrace();
			LOG.info("登陆系统异常" + e.toString());
		}
		return msg;
	}

	/**
	 * 得到用户的List集合
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<User> getUserList() {
		request = ServletActionContext.getRequest();
		session = request.getSession();
		/* 得到所有的用户集合 */
		List<User> userList = userDao.findByHql("from User u " + (((User) session.getAttribute("User")).getUserID() == 1 ? "" : " where u.userID!=1"));

		/* 遍历所有用户的用户组 */
		for (User user : userList) {
			StringBuffer userGroupNameSb = new StringBuffer();
			for (UserGroup userGroup : user.getUserGroups()) {
				userGroupNameSb.append(userGroup.getName() + ",");
			}
			user.setUserGroupNames(userGroupNameSb.toString().substring(0, userGroupNameSb.length() - 1));
		}
		return userList;
	}

	/**
	 * 得到所有的用户组的集合，去掉开发者权限
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<UserGroup> getUserGroupListAbsentAdmin() {
		List<UserGroup> userGroupList = userGroupDao.findByHql("from UserGroup ug where ug.groupID!=1");
		return userGroupList;
	}

	/**
	 * 保存用户
	 */
	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public Message saveUser(User user) {
		request = ServletActionContext.getRequest();
		session = request.getSession();
		Message msg = new Message();
		// 判断用户名是否存在
		if (userDao.findByHql("from User u  where u.account='" + user.getAccount() + "'").size() != 0) {
			msg.setMsgFlag(false);
			msg.setMsgStr("用户名重复！");
			return msg;
		}
		try {
			user.setPassword(MD5Util.md5_16(user.getPassword()));
		} catch (Exception e) {
			LOG.info("用户管理-新增用户-Md5加密异常" + e);
			msg.setMsgFlag(false);
			msg.setMsgStr("密码加密异常！");
			return msg;
		}
		user.setUserGroups(new HashSet<UserGroup>());
		/* 将用户选择的用户组放入set中 */
		List<UserGroup> userGroupList = userGroupDao.findByHql("from UserGroup u where u.groupID in (" + user.getUserGroupNames() + ")");
		for (UserGroup userGroup : userGroupList) {
			user.getUserGroups().add(userGroup);
		}

		user.setCreaterID(((User) session.getAttribute("User")).getUserID());
		user.setAddTime(new Date());
		user.setStatus(1);
		userDao.save(user);
		msg.setMsgFlag(true);
		msg.setMsgStr("保存成功！");
		return msg;
	}

	/**
	 * 删除用户
	 */
	@SuppressWarnings("unchecked")
	@Transactional
	@Override
	public Message deleteUser(String userIDs) {
		Message msg = new Message();
		if (userIDs.trim().isEmpty() || userIDs.trim() == "") {
			msg.setMsgFlag(false);
			msg.setMsgStr("删除的编号不能为空！");
			return msg;
		}
		final String hql = "from User u where u.userID in (" + userIDs + ")";
		List<User> users = userDao.findByHql(hql);

		for (User user : users) {
			try {
				LOG.info("开始删除用户编号为：" + user.getUserID());
				userDao.delete(user);
			} catch (Exception e) {
				LOG.info("删除用户失败，编号为：" + user.getUserID());
				msg.setMsgFlag(false);
				msg.setMsgStr("删除失败！");
				throw new RuntimeException("删除用户异常");
			}
		}

		msg.setMsgFlag(true);
		msg.setMsgStr("操作成功！");

		return msg;
	}

	/**
	 * 通过User 信息获取用户详情
	 */
	@Override
	public User getUserInfo(User user) {

		user = userDao.findById(user.getUserID());

		StringBuffer userGroupNameSb = new StringBuffer();
		for (UserGroup userGroup : user.getUserGroups()) {
			userGroupNameSb.append(userGroup.getGroupID() + ",");
		}
		user.setUserGroupNames(userGroupNameSb.toString().substring(0, userGroupNameSb.length() - 1));

		return user;
	}

	/**
	 * 执行更新操作
	 */
	@SuppressWarnings("unchecked")
	@Transactional
	@Override
	public Message updateUser(User user) {

		// 找到数据库中的对应的用户实例
		User u = new User();
		u = userDao.findById(user.getUserID());

		// 判断数据库中是否有此用户
		if (u == null) {
			message.setMsgFlag(false);
			message.setMsgStr("更新失败，用户ID不存在");
			return message;
		}

		try {
			if (!user.getPassword().trim().isEmpty() || user.getPassword().trim() != "") {
				u.setPassword(MD5Util.md5_16(user.getPassword()));
			}
		} catch (Exception e) {
			LOG.info("用户管理-新增用户-Md5加密异常" + e);
			message.setMsgFlag(false);
			message.setMsgStr("密码加密异常！");
			return message;
		}
		u.setName(user.getName());
		u.setAccount(user.getAccount());
		u.setDescription(user.getDescription());

		u.setUserGroups(new HashSet<UserGroup>());
		List<UserGroup> userGroupList = userGroupDao.findByHql("from UserGroup u where u.groupID in (" + user.getUserGroupNames() + ")");
		for (UserGroup userGroup : userGroupList) {
			u.getUserGroups().add(userGroup);
		}
		try {
			userDao.saveOrUpdate(userDao.getHibernateTemplate().merge(u));
			message.setMsgFlag(true);
			message.setMsgStr("保存成功！");
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new RuntimeException();
		}

		return message;
	}

	public List<ZTreeV> getZtreeList(User user) {
		user = userDao.findById(user.getUserID());
		List<ZTreeV> ztreeList = new ArrayList<ZTreeV>();
		// 获取所有功能List
		List<Fun> funList = funDao.findAll();
		// 获取该用户组已有权限的List
		Set<Fun> userFunSet = user.getFuns();

		for (Fun fun : funList) {
			ZTreeV z = new ZTreeV();
			z.id = fun.getFunID() + "";
			z.pId = fun.getParentFunID() + "";
			z.name = fun.getFunName();
			z.open = fun.getParentFunID() == 0;
			z.chkDisabled = false;
			z.Checked = false;
			// 判断用户是否有这个功能
			for (Fun fun2 : userFunSet) {
				if (fun2.getFunID().equals(fun.getFunID())) {
					z.Checked = true;
					break;
				}
			}
			// 判断用户组是否有这个功能
			for (UserGroup userGroup : user.getUserGroups()) {
				for (Fun fun3 : userGroup.getFuns()) {
					if (fun3.getFunID().equals(fun.getFunID())) {
						z.Checked = true;
						z.chkDisabled = true;
						break;
					}
				}
			}
			ztreeList.add(z);
		}

		return ztreeList;
	}

	// 保存权限
	@SuppressWarnings("unchecked")
	@Transactional
	public Message saveTree(User user) {

		try {

			User u = userDao.findById(user.getUserID());
			u.setFuns(new HashSet<Fun>());

			if (user.getUserGroupNames() != "" && !user.getUserGroupNames().isEmpty()) {
				List<Fun> funList = funDao.findByHql("from Fun a where a.funID in (" + user.getUserGroupNames() + ")");
				for (Fun fun : funList) {
					u.getFuns().add(fun);
				}
			}
			
			userDao.saveOrUpdate(userDao.getHibernateTemplate().merge(u));
			message.setMsgFlag(true);
			message.setMsgStr("操作成功！");
		} catch (Exception ex) {
			ex.printStackTrace();
			LOG.info("保存用户权限树异常");
			throw new RuntimeException();

		}

		return message;
	}

}
